#ifndef SERIALMANAGER_H
#define SERIALMANAGER_H

#include <QObject>
#include <QSerialPort>
#include <QByteArray>

class SerialPortManager : public QObject
{
    Q_OBJECT
public:
    explicit SerialPortManager(bool isSimulate = false, QObject *parent = nullptr);
    ~SerialPortManager() override;

    bool initSerialPort(const QString &portName, qint32 baudRate,
                       QSerialPort::DataBits dataBits,
                       QSerialPort::Parity parity,
                       QSerialPort::StopBits stopBits);

    // 修改返回类型为bool
    bool sendData(const QByteArray &data);

    void closeSerialPort();
    bool isSerialPortOpen() const;
    QString getPortName() const { return m_portName; }
    QStringList scanAvailablePorts();

signals:
    void dataReceived(const QString &portName, const QByteArray &data);
    void portStatusChanged(const QString &portName, const QString &statusInfo, bool isNormal = false);
    void availablePortsChanged(const QStringList &ports);

private slots:
    void onReadyRead();

private:
    QSerialPort *m_serialPort;
    QString m_portName;

    QByteArray m_dataBuffer;  // 缓存不完整数据
    const QByteArray m_frameSeparator = "\n";  // 帧分隔符（NMEA 用换行符）

    bool m_isSimulate{false}; // 模拟标志位
};

#endif // SERIALMANAGER_H
